/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */

Ext.namespace("Admin");

/**
 * Organization combo.
 *
 * @param config the config.
 */
Admin.OrganizationCombo = function(config) {
	Admin.OrganizationCombo.superclass.constructor.call(this, config);
};

Ext.extend(Admin.OrganizationCombo, Ext.form.ComboBox, {

	initComponent: function() {

		this.fieldLabel = MSG['user.organization'];
		this.hiddenName = 'organization';
		this.width = 140;
		this.store = new Ext.data.JsonStore({
			url: CONTEXT_PATH + '/secure/admin/organizations.json',
			root: 'results',
			fields: ['id', 'name']
		});
		this.tpl = new Ext.XTemplate(
				'<tpl for="."><div class="search-item">',
				'<h3>{name}</h3>',
				'{id} - {name}',
				'</div></tpl>'
				);

		this.itemSelector = 'div.search-item';
		this.minChars = 2;
		this.typeAhead = false;
		this.valueField = 'id';
		this.displayField = 'name';
		this.triggerAction = 'all';

		this.listeners = {
			blur: function () {
				if (this.getRawValue() == "") {
					this.clearValue();
				}
			}
		};

		Admin.OrganizationCombo.superclass.initComponent.call(this);
	},

	setValue: function(v) {
		// See https://yui-ext.com/forum/showthread.php?t=20803

		// If the ComboBox hasn't been loaded yet, load it asynchronously
		// before setting the value.
		if (this.mode == 'remote' && this.store.getCount() == 0) {
			this.store.on("load", function () {
				Admin.OrganizationCombo.superclass.setValue.call(this, v);
			}, this, {single: true});
			this.doQuery(this.allQuery, true);
		} else {
			Admin.OrganizationCombo.superclass.setValue.call(this, v);
		}
	}

});


/**
 * User edit dialog.
 *
 * @param config the configuration.
 */
Admin.UserDialog = function(config) {
	Admin.UserDialog.superclass.constructor.call(this, config);
};

Ext.extend(Admin.UserDialog, Ext.Window, {

	initComponent: function() {

		Ext.apply(this, {
			renderTo: Ext.getBody(),
			modal: true,
			iconCls: 'icon-user-add',
			title: MSG['user.data'],
			bodyStyle:'padding:5px'
		});

		this.items = new Ext.FormPanel({
			width: 340,
			labelWidth: 120,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'hidden',
				name: 'id',
				value: 0
			}, {
				xtype: 'textfield',
				name: 'login',
				fieldLabel: MSG['user.login'],
				maxLength: 30,
				allowBlank: false
			}, {
				xtype: 'textfield',
				name: 'fullname',
				fieldLabel: MSG['user.fullname'],
				maxLength: 30,
				allowBlank: false,
				vtype :'fullName'
			}, {
				xtype: 'textfield',
				name: 'email',
				fieldLabel: MSG['user.email'],
				vtype: 'email',
				maxLength: 50,
				allowBlank: false
			}, new Common.LanguageCombo({
				hiddenName: 'language',
				allowBlank: false
			}),{
				xtype: 'simplecombo',
				hiddenName: 'role',
				fieldLabel: MSG['user.role'],
				data: Common.Roles,
				width: 140,
				allowBlank: false
			}, new Admin.OrganizationCombo({allowBlank: false}),{
				xtype: 'textfield',
				name: 'password',
				fieldLabel: MSG['user.password'],
				inputType: 'password',
				maxLength: 12,
				allowBlank: false
			}, {
				xtype: 'textfield',
				name: 'password-repeated',
				labelSeparator: '',
				inputType: 'password',
				maxLength: 12,
				allowBlank: false,
				vtype: 'repeated',
				repeatedField: 'password'
			}],
			buttons: [{
				text: MSG['button.save'],
				iconCls: 'icon-disk',
				handler: this.onSave,
				scope: this
			}, {
				text: MSG['button.cancel'],
				iconCls: 'icon-cancel',
				handler: this.onCancel,
				scope: this
			}]
		});


		Admin.UserDialog.superclass.initComponent.call(this);
	},

	onSave: function() {
		var theForm = this.items.items[0].getForm();

		theForm.submit({
			url: CONTEXT_PATH + '/secure/admin/user/update.json',
			method: 'POST',
			clientValidation: true,
			waitTitle: MSG['wait.title'],
			waitMsg: MSG['wait.message'],
			success: this.onSaveSuccess,
			failure: this.onSaveError,
			scope: this
		});
	},

	onCancel: function() {
		this.close();
	},

	onSaveSuccess: function(/*form, action*/) {
		this.close();
		notifySuccess(MSG['user.update'], MSG['update.success']);
	},

	onSaveError: function(/*form, action*/) {
		notifyError(MSG['user.update'], MSG['update.error']);
	}

});


/**
 *	User search panel.
 *
 * @param config the configuration.
 */
Admin.UserSearchPanel = function(config) {
	Admin.UserSearchPanel.superclass.constructor.call(this, config);
};

Ext.extend(Admin.UserSearchPanel, Ext.Panel, {

	searchForm: null,

	waitDlg: null,

	resultsStore: null,

	pageToolbar: null,

	resultsGrid: null,

	editForm: null,

	initComponent: function() {

		this.layout = 'border';
		this.title = MSG['users.title'];
		this.closable = true;
		this.autoShow = true;
		this.iconCls = 'icon-glist';

		// Tools
		this.tools = [{
			id: 'close',
			handler: this.onClose,
			scope: this
		}];

		// Search form
		this.searchForm = new Ext.FormPanel({
			region: 'west',
			split: true,
			collapsible: true,
			title: MSG['search.title'],
			width: 340,
			labelWidth: 120,
			//autoHeight: true,
			//frame:true,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'textfield',
				name: 'login',
				fieldLabel: MSG['user.login']
			}, {
				xtype: 'textfield',
				name: 'fullname',
				fieldLabel: MSG['user.fullname'],
				maxLength: 30
			}, {
				xtype: 'textfield',
				name: 'email',
				fieldLabel: MSG['user.email'],
				maxLength: 50
			}, new Common.LanguageCombo({
				hiddenName: 'language'
			}), {
				xtype: 'simplecombo',
				hiddenName: 'role',
				fieldLabel: MSG['user.role'],
				data: Common.Roles,
				width: 140,
				allowBlank: false
			}, new Admin.OrganizationCombo()
			],
			buttons: [{
				text: MSG['button.search'],
				iconCls: 'icon-search',
				handler: this.onSearch,
				scope: this
			}, {
				text: MSG['button.reset'],
				iconCls: 'icon-cancel',
				handler: this.onReset,
				scope: this
			}]
		});

		// Store
		this.resultsStore = new Ext.data.JsonStore({
			url: CONTEXT_PATH + '/secure/admin/user/find.json',
			root: 'results',
			totalProperty: 'total',
			remoteSort: true,
			fields: ['id', 'fullname', 'login', 'email', 'disableDate', 'language', 'role', 'organization']
		});
		this.resultsStore.on("beforeload",
				function() {
					this.waitDlg = Ext.Msg.wait(MSG['wait.title'], MSG['wait.text']);
					this.resultsStore.baseParams = this.searchForm.getForm().getRawValues();
				}, this);
		this.resultsStore.on("load",
				function() {
					this.waitDlg.hide();
				}, this);

		// Pagination toolbar
		this.pageToolbar = new Ext.PagingToolbar({
			store: this.resultsStore,
			displayInfo: true,
			pageSize: 100,
			plugins: [new Common.PageSizePlugin(MSG['page.size'])]
		});

		// Grid
		this.resultsGrid = new Ext.grid.GridPanel({
			title: MSG['result.title'],
			region: 'center',
			//autoHeight: true,
			viewConfig: {
				emptyText: MSG['pagination.empty'],
				forceFit: true
			},
			// ['id', 'fullname', 'login', 'email', 'language', 'role', 'organization']
			cm: new Ext.grid.ColumnModel([
				{header: MSG['user.id'], dataIndex: 'id', width: 20, sortable: true},
				{header: MSG['user.fullname'], dataIndex: 'fullname', width: 140, sortable: true},
				{header: MSG['user.login'], dataIndex: 'login', width: 100, sortable: true},
				{header: MSG['user.email'], dataIndex: 'email', width: 190, sortable: true},
				{header: MSG['user.disabled'], dataIndex: 'disableDate', width: 70, sortable: false},
				{header: MSG['user.language'], dataIndex: 'language', width: 70, sortable: true, renderer: function(r) {
					return MSG[r];
				}},
				{header: MSG['user.role'], dataIndex: 'role', width: 100, sortable: true, renderer: function(r) {
					return MSG[r.name];
				}},
				{header: MSG['user.organization'], dataIndex: 'organization', width: 100, sortable: true, renderer: function(r) {
					return r.name;
				}}
			]),
			store: this.resultsStore,
			bbar: this.pageToolbar
		});

		// Editor
		this.editForm = new Ext.FormPanel({
			region: 'east',
			split: true,
			collapsible: true,
			collapsed: true,
			title: MSG['button.new'],
			//autoHeight: true,
			width: 340,
			labelWidth: 120,
			//frame:true,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'hidden',
				name: 'id',
				value: 0
			}, {
				xtype: 'textfield',
				name: 'login',
				fieldLabel: MSG['user.login'],
				maxLength: 20,
				allowBlank: false
			}, {
				xtype: 'textfield',
				name: 'fullname',
				fieldLabel: MSG['user.fullname'],
				maxLength: 30,
				allowBlank: false,
				vtype :'fullName'
			}, {
				xtype: 'textfield',
				name: 'email',
				vtype: 'email',
				fieldLabel: MSG['user.email'],
				maxLength: 50,
				allowBlank: false
			}, new Common.LanguageCombo({
				hiddenName: 'language',
				allowBlank: false
			}),{
				xtype: 'simplecombo',
				hiddenName: 'role',
				fieldLabel: MSG['user.role'],
				data: Common.Roles,
				width: 140,
				allowBlank: false
			}, new Admin.OrganizationCombo({allowBlank: false}), {
				xtype: 'simplecombo',
				hiddenName: 'disableDate',
				fieldLabel: MSG['user.disabled'],
				data: Common.YesNo,
				width: 140,
				allowBlank: false
			}, {
				xtype: 'textfield',
				name: 'password',
				fieldLabel: MSG['user.password'],
				inputType: 'password',
				maxLength: 12
			}, {
				xtype: 'textfield',
				name: 'password-repeated',
				labelSeparator: '',
				inputType: 'password',
				maxLength: 12,
				vtype: 'repeated',
				repeatedField: 'password'
			}],
			buttons: [{
				text: MSG['button.save'],
				iconCls: 'icon-disk',
				handler: this.onSave,
				scope: this
			}, {
				text: MSG['button.cancel'],
				iconCls: 'icon-cancel',
				handler: this.onCancel,
				scope: this
			}]
		});

		this.items = [this.searchForm, this.resultsGrid, this.editForm];

		this.pageToolbar.doLoad(0);

		this.resultsGrid.on("rowclick", this.onSelected, this);
		// this.resultsGrid.on("rowcontextmenu", this.onContextMenu, this);

		Admin.UserSearchPanel.superclass.initComponent.call(this);
	},

	onClose: function() {
		Main.app.addPanel(null);
	},

	onSearch: function() {
		this.editForm.collapse();
		this.pageToolbar.doLoad(0);
	},

	onReset: function() {
		this.searchForm.getForm().reset();
		this.pageToolbar.doLoad(0);
	},

	onSelected: function(grid, rowIndex/*, evt*/) {
		this.searchForm.collapse();
		this.editForm.expand();

		var record = grid.getStore().getAt(rowIndex);
		var data = {};
		Ext.apply(data, record.data);
		data.role = record.data.role.id;
		data.organization = record.data.organization.id;
		if (record.data.disableDate.length > 0) {
			data.disableDate = 'true';
		} else {
			data.disableDate = 'false';
		}

		// Remote combo set value... https://yui-ext.com/forum/showthread.php?t=20803

		this.editForm.getForm().loadRecord({data: data});
		this.editForm.setTitle(MSG['edit.title']);
	},

	onSave: function() {
		var theForm = this.editForm.getForm();

		theForm.submit({
			url: CONTEXT_PATH + '/secure/admin/user/update.json',
			method: 'POST',
			clientValidation: true,
			waitTitle: MSG['wait.title'],
			waitMsg: MSG['wait.message'],
			success: this.onSaveSuccess,
			failure: this.onSaveError,
			scope: this
		});
	},

	onSaveSuccess: function(/*form, action*/) {
		notifySuccess(MSG['update'], MSG['update.success']);
		this.pageToolbar.onClick("refresh");
	},

	onSaveError: function(/*form, action*/) {
		notifyError(MSG['update'], MSG['update.error']);
	},

	onCancel: function() {
		this.editForm.getForm().reset();
	  this.editForm.setTitle(MSG['button.new']);
		this.editForm.getForm().findField('organization').setValue(Main.app.getUser().organization.id);
	}

});

// Register user search panel
Ext.reg('user-search', Admin.UserSearchPanel);


/**
 * Module definition.
 */
MODULES['2_admin'] = {

	menu: null,

	init: function() {

		// Initialize common menu
		this.menu = new Ext.menu.Menu({
			items: [{
				text: MSG['user.search'],
				iconCls: 'icon-user-find',
				handler: this.onFindUsers,
				scope: this
			},{
				text: MSG['user.new'],
				iconCls: 'icon-user-add',
				handler: this.onNewUser,
				scope: this
			}]
		});


		// Add menu to toolbar
		Main.app.mainToolbar.add({
			text: MSG['user.multiple'],
			iconCls: 'icon-glist',
			menu: this.menu
		});

	},

	onFindUsers: function() {
		var searchPanel = new Admin.UserSearchPanel();
		Main.app.addPanel(searchPanel);
	},

	onNewUser: function() {
		// Add new tab
		var userDialog = new Admin.UserDialog();
		userDialog.show();
	}

};